package com.you.learning.rabbitmq.javaamqp.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitMQConsumer2 {

    //交换机的名称
    private final static String DIRECT_EXCHANGE_NAME = "TEST_DIRECT_EXCHANGE_NAME"; //直连模式的交换机路由方式

    private final static String TOPIC_EXCHANGE_NAME = "TEST_TOPIC_EXCHANGE_NAME"; //主题模式的交换机路由方式

    private final static String FANOUT_EXCHANGE_NAME = "TEST_FANOUT_EXCHANGE_NAME"; //广播模式的交换机路由方式

    private final static String QUEUE_NAME1 = "TEST_QUEUE_NAME1";

    private final static String QUEUE_NAME2 = "TEST_QUEUE_NAME2";

    private final static String QUEUE_NAME3 = "TEST_QUEUE_NAME3";

    private final static String ROUTE_KEY = "DIRECT_ROUTE_KEY";

    public static void main(String[] args) throws IOException, TimeoutException {
        try {
            // 创建连接工厂
            ConnectionFactory connectionFactory = new ConnectionFactory();
            // 设置连接的broker(rabbitmq服务器)地址和IP
            connectionFactory.setHost("192.168.56.101");
            connectionFactory.setPort(5672);
            //设置虚拟机
            connectionFactory.setVirtualHost("/");
            //用户密码在安装rabbitmq的时候创建的
            connectionFactory.setUsername("admin");
            connectionFactory.setPassword("admin");
            // 获取连接
            Connection connection = connectionFactory.newConnection();
            // 创建通道
            Channel channel = connection.createChannel();
            /**
             * 消费消息
             * queue 队列名称
             * autoAck true，消费端收到消息后，队列自动删除消息
             *         false，消费端收到消息后，需手动删除消息
             * callback 消费者对象
             */
            channel.basicConsume(QUEUE_NAME1, true, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag,
                                           Envelope envelope,
                                           AMQP.BasicProperties properties,
                                           byte[] body) throws IOException {
                    String msg = new String(body, "UTF-8");
                    //TODO 自己的业务
                    System.out.println("Received message : " + msg);
                    // 处理完业务之后，手动删除消息
//                    this.getChannel().basicAck(envelope.getDeliveryTag(), false);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
